package guitforl.view

import guitforl.builders.TabBuilder
import org.eclipse.swt.SWT
import org.eclipse.swt.layout.{FillLayout}
import org.eclipse.swt.widgets.{TabItem, TabFolder, Shell, Display}

import scala.xml._

import guitforl.wrappers.TabWrapper

class Form {
  val display: Display = new Display
  val shell: Shell = new Shell(display)
  val folder: TabFolder = new TabFolder(shell, SWT.NONE)

  val templatesFolder: String = "./templates/"
  val realization: NodeSeq = XML.load(templatesFolder + "implementation.xml")

  def buildTabs(): Unit = {
    val path = new java.io.File(templatesFolder)
    val fileNames = path.list.filter(name => name.endsWith(".xml"))

    for{tabBlock <- (realization \ "tab")} {
      val template = XML.load(templatesFolder + (tabBlock \ "@template") + ".xml")
      val wrapTab: TabWrapper = new TabWrapper {
        val name = (tabBlock \ "@name").text
        val tab = new TabItem(folder, SWT.NONE)
      }
      wrapTab.init((tabBlock \ "@template") + ".xml")
      TabBuilder.buildTab(folder, wrapTab, template)
      //implementationReader.read(tabBlock, wrapTab)
      println(wrapTab)
    }
  }

  def run(): Unit = {
    prepareShell
    permanentPrepare
    buildTabs

    shell open

    while (!shell.isDisposed)
      if (!display.readAndDispatch) display.sleep
    display.dispose
  }


  def permanentPrepare() = {
    shell.setLayout(new FillLayout())
    folder.setSize(shell.getSize().x - 15, shell.getSize().y - 35);
  }

  def prepareShell(): Unit = {
    val maxWidth = display.getPrimaryMonitor().getBounds().width;
    val maxHeight = display.getPrimaryMonitor().getBounds().height;
    shell.setSize(maxWidth / 2, maxHeight / 2);

    val clientWidth = display.getPrimaryMonitor().getBounds().width;
    val clientHeight = display.getPrimaryMonitor().getBounds().height;
    val shellWidth = shell.getBounds().width;
    val shellHeight = shell.getBounds().height;
    shell.setLocation((clientWidth - shellWidth) / 2 + 25, (clientHeight - shellHeight) / 2);
  }

}
